package com.pishou.player;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.pishou.Data;
import com.pishou.ParamConfig;
import com.pishou.code.thread.UpdateDataLoop;
import com.pishou.code.thread.UpdatePlayList;
import com.pishou.code.util.FileAction;
import com.pishou.code.util.NetWork;
import com.pishou.code.util.VideoPlayList;
import com.pishou.shop.GifActivity;
import com.pishou.shop.NoticeActivity;

import java.lang.reflect.Array;
import java.util.Timer;
import java.util.TimerTask;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class TextureActivity extends Activity  implements TextureView.SurfaceTextureListener {

    private IjkMediaPlayer mp;
    private TextureView tv;
    private Surface surface;

    private Timer timer;
    private TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.texture_activity);

        // 第一次启动该页面执行
        if (!Data.startUp){
            Data.startUp = true;
            // 设置文件路径
            ParamConfig.file_path = getFilesDir().getPath();
            // 清空上一次下载失败的文件
            FileAction.delAllFile(ParamConfig.file_path+"/temp");
            new Thread(){
                @Override
                public void run() {
                    try{
                        Thread.sleep(5 * 1000l);
                        Data.setData(false,true);
                        // 更新播放列表
                        Thread t = new UpdatePlayList(ParamConfig.getConfig_json().getInteger("playerId"));
                        t.start();
                        // 循环更新数据
                        Thread updateDataLoop = new UpdateDataLoop();
                        updateDataLoop.start();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    super.run();
                }
            }.start();

        }
        if (Data.carts.size()>0){
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    Data.clearCart();
                }
            };
            timer.schedule(task,60*1000l);
        }


        tv = findViewById(R.id.texture);
        tv.setSurfaceTextureListener(this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 点击事件中触发两次，只在点下时执行
        if(ev.getAction()==0){
            if (NetWork.isNetworkConnected(getApplicationContext())){
                Intent intent = new Intent(getApplicationContext(), GifActivity.class);
                startActivity(intent);
            }else{
                Intent intent = new Intent(getApplicationContext(), NoticeActivity.class);
                intent.putExtra("notice","没有网络连接，请稍候再试！");
                startActivity(intent);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        surface = new Surface(surfaceTexture);
        new PlayVideo().start();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        surfaceTexture = null;
        surface = null;
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

    }

    private class PlayVideo extends  Thread{
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
            try{
                mp = new IjkMediaPlayer();
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "videotoolbox", 1);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"); //根据媒体类型来配置
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1048576);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 0);  // 无限读
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 1000L);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1L);
                //  关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0L);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1L);

                mp.setDataSource(VideoPlayList.getNextVideoPath());
                mp.prepareAsync();
                mp.setSurface(surface);
                mp.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(IMediaPlayer iMediaPlayer) {
                        mp.start();
                    }
                });
                mp.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(IMediaPlayer iMediaPlayer) {
                        mp.reset();
                        if (VideoPlayList.target.equals("Ad") && VideoPlayList.getCurrentVideo() != null ){
                            Intent intent = new Intent(getApplicationContext(),AdCommentVideoActivity.class);
                            startActivity(intent);
                        }else{
                            new PlayVideo().start();
                        }
                    }
                });

            }catch (Exception e){
                e.printStackTrace();
            }
            super.run();
        }
    }

    @Override
    protected void onStop() {
        if (mp != null && mp.isPlaying()){
            mp.stop();
            mp.release();
        }
        super.onStop();
    }

    @Override
    protected void onPause() {
        if (timer!=null){
            timer.cancel();
            timer=null;
        }
        if (task!=null){
            task.cancel();
            task=null;
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        if (mp!=null){
            mp.reset();
            new PlayVideo().start();
        }
        super.onStart();
    }
}
